<template>
  <div class="tenant-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>租户管理</h2>
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        创建租户
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <div class="search-form">
      <el-form :inline="true" :model="searchForm" @submit.prevent="loadTenantList">
        <el-form-item label="租户名称">
          <el-input 
            v-model="searchForm.tenantName" 
            placeholder="请输入租户名称"
            clearable 
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="租户状态">
          <el-select 
            v-model="searchForm.status" 
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
            <el-option label="试用" :value="2" />
            <el-option label="过期" :value="3" />
            <el-option label="待审核" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="租户类型">
          <el-select 
            v-model="searchForm.tenantType" 
            placeholder="请选择类型"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="企业版" value="ENTERPRISE" />
            <el-option label="标准版" value="STANDARD" />
            <el-option label="试用版" value="TRIAL" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadTenantList" :loading="loading">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 租户列表表格 -->
    <el-table 
      :data="tenantList" 
      style="width: 100%" 
      v-loading="loading"
      row-key="id"
      stripe
    >
      <el-table-column prop="tenantId" label="租户ID" width="120" fixed="left" />
      <el-table-column prop="tenantName" label="租户名称" min-width="150" show-overflow-tooltip />
      <el-table-column prop="tenantType" label="租户类型" width="100">
        <template #default="{ row }">
          <el-tag :type="getTenantTypeTagType(row.tenantType)">
            {{ getTenantTypeText(row.tenantType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.status)">
            {{ row.statusText }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="用户数量" width="120">
        <template #default="{ row }">
          <div class="user-quota">
            <span>{{ row.userCount || 0 }}</span>
            <span v-if="row.maxUsers" class="quota-max">/ {{ row.maxUsers }}</span>
            <span v-else class="quota-unlimited">/ 无限制</span>
          </div>
          <el-progress
            v-if="row.maxUsers"
            :percentage="getUserQuotaPercentage(row)"
            :color="getQuotaColor(row)"
            :show-text="false"
            :stroke-width="6"
            style="margin-top: 4px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="expireTime" label="过期时间" width="180">
        <template #default="{ row }">
          <div v-if="row.expireTime">
            <div>{{ formatDateTime(row.expireTime) }}</div>
            <el-tag v-if="row.nearExpiry" type="danger" size="small" style="margin-top: 2px">即将过期</el-tag>
          </div>
          <span v-else>永久</span>
        </template>
      </el-table-column>
      <el-table-column prop="contactName" label="联系人" width="100" show-overflow-tooltip />
      <el-table-column prop="createdAt" label="创建时间" width="150">
        <template #default="{ row }">
          {{ formatDateTime(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button size="small" @click="showTenantStats(row)">
              <el-icon><DataAnalysis /></el-icon>
              统计
            </el-button>
            <el-button size="small" @click="editTenant(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
          </el-button-group>
          
          <el-dropdown 
            @command="(command) => handleDropdownAction(command, row)"
            style="margin-left: 8px"
          >
            <el-button size="small">
              更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item 
                  :command="`status:${row.status === 1 ? 0 : 1}`"
                  :icon="row.status === 1 ? 'CircleClose' : 'CircleCheck'"
                >
                  {{ row.status === 1 ? '禁用' : '启用' }}
                </el-dropdown-item>
                <el-dropdown-item 
                  command="delete" 
                  divided
                  :icon="Delete"
                  style="color: var(--el-color-danger)"
                >
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.current"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadTenantList"
        @current-change="loadTenantList"
      />
    </div>

    <!-- 创建/编辑租户对话框 -->
    <TenantFormDialog
      v-model="showDialog"
      :tenant="currentTenant"
      @success="loadTenantList"
    />

    <!-- 租户统计对话框 -->
    <TenantStatsDialog
      v-model="showStatsDialog"
      :tenant-id="currentTenantId"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, ArrowDown, DataAnalysis, Edit, Delete } from '@element-plus/icons-vue'
import TenantFormDialog from './components/TenantFormDialog.vue'
import TenantStatsDialog from './components/TenantStatsDialog.vue'
import { tenantApi } from '@/api/tenant'
import type { TenantDTO } from '@/types/api'
import { formatDate } from '@/utils/date'

// 响应式数据
const loading = ref(false)
const showDialog = ref(false)
const showStatsDialog = ref(false)
const currentTenant = ref<TenantDTO | null>(null)
const currentTenantId = ref<string>('')

const tenantList = ref<TenantDTO[]>([])
const searchForm = reactive({
  tenantName: '',
  status: '' as number | string,
  tenantType: '' as string,
})

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
})

// 方法
const loadTenantList = async () => {
  loading.value = true
  try {
    const response = await tenantApi.queryTenants({
      current: pagination.current,
      size: pagination.size,
      tenantName: searchForm.tenantName || undefined,
      status: searchForm.status ? Number(searchForm.status) : undefined,
      tenantType: searchForm.tenantType || undefined,
    })
    
    if (response.success) {
      tenantList.value = response.data.records
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取租户列表失败')
    }
  } catch (error) {
    console.error('获取租户列表失败:', error)
    ElMessage.error('获取租户列表失败')
  } finally {
    loading.value = false
  }
}

const showCreateDialog = () => {
  currentTenant.value = null
  showDialog.value = true
}

const editTenant = (tenant: TenantDTO) => {
  currentTenant.value = { ...tenant }
  showDialog.value = true
}

const showTenantStats = (tenant: TenantDTO) => {
  currentTenantId.value = tenant.tenantId!
  showStatsDialog.value = true
}

const handleDropdownAction = async (command: string, tenant: TenantDTO) => {
  if (command.startsWith('status:')) {
    const newStatus = parseInt(command.split(':')[1])
    await updateTenantStatus(tenant.tenantId!, newStatus)
  } else if (command === 'delete') {
    await deleteTenant(tenant)
  }
}

const updateTenantStatus = async (tenantId: string, status: number) => {
  try {
    const response = await tenantApi.updateTenantStatus(tenantId, status)
    if (response.success) {
      ElMessage.success('租户状态更新成功')
      await loadTenantList()
    } else {
      ElMessage.error(response.message || '租户状态更新失败')
    }
  } catch (error) {
    console.error('租户状态更新失败:', error)
    ElMessage.error('租户状态更新失败')
  }
}

const deleteTenant = async (tenant: TenantDTO) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除租户 "${tenant.tenantName}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await tenantApi.deleteTenant(tenant.tenantId!)
    if (response.success) {
      ElMessage.success('租户删除成功')
      await loadTenantList()
    } else {
      ElMessage.error(response.message || '租户删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('租户删除失败:', error)
      ElMessage.error('租户删除失败')
    }
  }
}

const resetSearch = () => {
  searchForm.tenantName = ''
  searchForm.status = ''
  searchForm.tenantType = ''
  pagination.current = 1
  loadTenantList()
}

// 辅助函数
const getTenantTypeText = (type?: string) => {
  const typeMap: Record<string, string> = {
    ENTERPRISE: '企业版',
    STANDARD: '标准版',
    TRIAL: '试用版',
  }
  return type ? typeMap[type] || type : '-'
}

const getTenantTypeTagType = (type?: string): 'primary' | 'success' | 'info' | 'warning' | 'danger' => {
  const typeMap: Record<string, 'primary' | 'success' | 'info' | 'warning' | 'danger'> = {
    ENTERPRISE: 'danger',
    STANDARD: 'primary',
    TRIAL: 'warning',
  }
  return type ? (typeMap[type] || 'info') : 'info'
}

const getStatusTagType = (status?: number): 'primary' | 'success' | 'info' | 'warning' | 'danger' => {
  const statusMap: Record<number, 'primary' | 'success' | 'info' | 'warning' | 'danger'> = {
    0: 'info',      // 禁用
    1: 'success',   // 正常
    2: 'warning',   // 试用
    3: 'danger',    // 过期
    4: 'info',      // 待审核
  }
  return status !== undefined ? (statusMap[status] || 'info') : 'info'
}

const getUserQuotaPercentage = (tenant: TenantDTO) => {
  if (!tenant.maxUsers || tenant.maxUsers <= 0) return 0
  const userCount = tenant.userCount || 0
  return Math.min((userCount / tenant.maxUsers) * 100, 100)
}

const getQuotaColor = (tenant: TenantDTO) => {
  const percentage = getUserQuotaPercentage(tenant)
  if (percentage >= 90) return '#f56c6c'  // 红色
  if (percentage >= 70) return '#e6a23c'  // 黄色
  return '#67c23a'  // 绿色
}

const formatDateTime = (dateTime?: string) => {
  return dateTime ? formatDate(dateTime, 'YYYY-MM-DD HH:mm') : '-'
}

// 生命周期
onMounted(() => {
  loadTenantList()
})
</script>

<style scoped>
.tenant-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.search-form {
  background: var(--el-bg-color);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  border: 1px solid var(--el-border-color-light);
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.user-quota {
  font-weight: 500;
}

.quota-max {
  color: var(--el-color-warning);
}

.quota-unlimited {
  color: var(--el-color-success);
  font-size: 12px;
}

:deep(.el-table__body-wrapper) {
  scrollbar-width: thin;
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
}

:deep(.el-dropdown-menu__item .el-icon) {
  margin-right: 8px;
}
</style>
